//
//  ScheduleCalendarView.m
//  MarryBackEnd
//
//  Created by mac on 2020/8/3.
//  Copyright © 2020 WPP. All rights reserved.
//

#import "ScheduleCalendarView.h"
#import "ScheduleCalendarCell.h"
#import "ScheduleCalendarModel.h"
#import "ScheduleCalendarServiceModel.h"
#define NumberMounthes 4
#define allCount 42
#import "NSDate+Category.h"
@interface ScheduleCalendarView ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong)UIView *headView;
@property(nonatomic,strong)UICollectionView *mainView;
@property(nonatomic,assign)NSInteger currentYear;
@property(nonatomic,assign)NSInteger currentMonth;
@property(nonatomic,assign)NSInteger currentDay;
@property(nonatomic,copy)NSString *currentToday;//2020-8-3
@property(nonatomic,copy)NSString *selectedDay;//2020-8-3
@property(nonatomic,assign)NSInteger currentIndex;
@property(nonatomic,strong)NSMutableArray<NSMutableArray<ScheduleCalendarModel *> *> *dataArr;
@end

@implementation ScheduleCalendarView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = WhiteColor;
        [self createProperty];
        [self createUI];
    }
    return self;
}
- (void)dealloc
{
    NSLog(@"ScheduleCalendarView ---dealloc");
}
- (void)createProperty
{
    
}
- (void)createUI
{
    [self headView];
    self.mainView.top = self.headView.bottom;
    self.height = self.mainView.bottom;
}
#pragma mark - setter
- (void)begin
{
    //清除所有数据...
    [self.dataArr removeAllObjects];
    //数据1
    NSDate *currentDate = [[NSDate alloc]init];
    NSInteger year = [NSDate year:currentDate];
    NSInteger month = [NSDate month:currentDate];
    NSInteger day = [NSDate day:currentDate];
    //数据2
    [self createDataWithYear:year withMonth:month withDay:day];
    [self scrollIndexPath:NumberMounthes shouldReloadData:YES animal:NO first:YES];
    self.currentIndex = NumberMounthes;
    //网络请求
    [self createNetManager:YES];
    //回调月份
    !self.BackMonthBlock ?: self.BackMonthBlock ([NSString stringWithFormat:@"%ld年%ld月",self.currentYear,self.currentMonth]);
    //回调年月日
    !self.BackDayTimeBlock ?: self.BackDayTimeBlock ([NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day]);
}
- (void)changeDateWithDayTime:(NSString *)dayTime
{
    //清除所有数据...
    [self.dataArr removeAllObjects];
    //数据1
    //2020-8-19
    NSArray<NSString *> *times = [dayTime componentsSeparatedByString:@"-"];
    if (times.count != 3) {
        return;
    }
    NSInteger year = times[0].integerValue;
    NSInteger month = times[1].integerValue;
    NSInteger day = times[2].integerValue;
    //数据2
    [self createDataWithYear:year withMonth:month withDay:day];
    [self scrollIndexPath:NumberMounthes shouldReloadData:YES animal:NO first:YES];
    self.currentIndex = NumberMounthes;
    //网络请求
    [self createNetManager:YES];
    //回调月份
    !self.BackMonthBlock ?: self.BackMonthBlock ([NSString stringWithFormat:@"%ld年%ld月",self.currentYear,self.currentMonth]);
    //回调年月日
    !self.BackDayTimeBlock ?: self.BackDayTimeBlock ([NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day]);
}
- (void)collectionBlockCallBack
{
    [self.dataArr[self.currentIndex] enumerateObjectsUsingBlock:^(ScheduleCalendarModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            NSLog(@"%@ %@",obj.isChoice,obj.dateStr);
        }
    }];
    [self.mainView reloadData];
}
#pragma mark - 处理数据
- (void)createDataWithYear:(NSInteger)year withMonth:(NSInteger)month withDay:(NSInteger)day
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    self.currentYear = year;
    self.currentMonth = month;
    self.currentDay = day;
    {
        self.selectedDay = [NSString stringWithFormat:@"%ld-%ld-%ld",self.currentYear,self.currentMonth,self.currentDay];
        NSDate *currentDate = [[NSDate alloc]init];
        self.currentToday = [NSString stringWithFormat:@"%ld-%ld-%ld",[NSDate year:currentDate],[NSDate month:currentDate],[NSDate day:currentDate]];
    }
    //2020-8-3
    //添加前4个月数据 7 6 5 4
    for (NSInteger index = 0; index < NumberMounthes; index ++) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArr addObject:array];
        [self updateDateYear:self.currentYear Month:(self.currentMonth - index - 1) index:index];
    }
    //排序 4 5 6 7
     [self.dataArr  sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
         return NSOrderedDescending;
    }];
    //添加当前月份
    NSMutableArray *array = [NSMutableArray array];
    [self.dataArr addObject:array];
    [self updateDateYear:self.currentYear Month:self.currentMonth index:NumberMounthes];
    //添加后4个月 9 10 11 12
    for (NSInteger index = 0; index < NumberMounthes; index ++) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArr addObject:array];
        [self updateDateYear:self.currentYear Month:(self.currentMonth + index + 1) index:index + NumberMounthes + 1];
    }
}
- (void)updateDateYear:(NSInteger)year Month:(NSInteger)month index:(NSInteger)index
{
    if (self.dataArr.count <= index) {
        return;
    }
    [self.dataArr[index]removeAllObjects];
    //处理年 月
    if (month > 12) {
        int num = (month/12.0);
        month = month - (num+1)*12 ;
        year += (num+1);
    }
    if (month < 1) {
        int num = (month/-12);
        month = month + (num+1)*12 ;
        year -= (num+1);
    }
    //zone dateFormatter
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    //components
    NSDateComponents *components = [[NSDateComponents alloc]init];
    components.month = month;
    components.year = year;
    components.day = 1;
    //calendar
    NSCalendar *calendar = [NSCalendar currentCalendar];
    //NDDate---now
    NSDate *nowDate = [calendar dateFromComponents:components];
    nowDate = [nowDate dateByAddingTimeInterval: [zone secondsFromGMTForDate: nowDate]];
    //NDDate---next
    if (components.month <= 1) {
        components.month = 12;
        components.year -= 1;
    }else{
        components.month -= 1;
    }
    NSDate *nextDate = [calendar dateFromComponents:components];
    nextDate = [nextDate dateByAddingTimeInterval: [zone secondsFromGMTForDate: nextDate]];
    //参数 DaysInNextMonth：下个月一共多少天 firstDayInThisMounth：当月下标 daysInThisMounth：当月一共多少天
    NSInteger DaysInNextMonth = [NSDate totaldaysInMonth:nextDate];
    NSInteger firstDayInThisMounth = [NSDate firstWeekdayInThisMonth:nowDate];
    NSInteger daysInThisMounth = [NSDate totaldaysInMonth:nowDate];
    NSInteger tmpDay = 0;
    
    NSMutableArray *currentArray = self.dataArr[index];
    for (NSInteger index = 0; index < allCount; index ++) {
        ScheduleCalendarModel *calendarModel = [[ScheduleCalendarModel alloc]init];
        NSInteger tmpYear = year;
        NSInteger tmpMonth = month;
        if (index < firstDayInThisMounth) {
            //lastMonth 上个月
            if (tmpMonth <= 1) {
                tmpMonth = 12;
                tmpYear -= 1;
            }else{
                tmpMonth -= 1;
            }
            tmpDay = DaysInNextMonth - firstDayInThisMounth + index + 1;
            calendarModel.monthType = MonthTypeLast;
            
        } else if (index > (daysInThisMounth + firstDayInThisMounth - 1)) {
            //nextMonth 下个月
            if (tmpMonth >= 12) {
                tmpMonth = 1;
                tmpYear += 1;
            }else{
                tmpMonth+= 1;
            }
            tmpDay = index - (daysInThisMounth + firstDayInThisMounth - 1);
            calendarModel.monthType = MonthTypeNext;
        } else {
            //current 本月
            tmpDay = index - firstDayInThisMounth + 1;
            calendarModel.monthType = MonthTypeCurrent;
        }
        NSString *detaMonth = tmpMonth<10?[NSString stringWithFormat:@"0%ld",tmpMonth]:[NSString stringWithFormat:@"%ld",tmpMonth];
        NSString *detaDay = tmpDay<10?[NSString stringWithFormat:@"0%ld",tmpDay]:[NSString stringWithFormat:@"%ld",tmpDay];
        NSString *dateStr = [NSString stringWithFormat:@"%ld-%@-%@",tmpYear,detaMonth,detaDay];
        NSDate *myDate = [dateFormatter dateFromString:dateStr];
        NSDictionary *dic = [NSDate getChineseCalendarWithDate:myDate Year:tmpYear Month:tmpMonth Day:tmpDay];
        calendarModel.year = tmpYear;
        calendarModel.month = tmpMonth;
        calendarModel.day = tmpDay;
        calendarModel.dateStr = dateStr;
        calendarModel.date = myDate;
        calendarModel.index = (index % 7 * 6 + index / 7);
        calendarModel.holday = [dic[@"holday"] boolValue];
        calendarModel.chineseName = dic[@"name"];
        calendarModel.chineseDetail = dic[@"detail"];
        //判断是否是当天的
        if ([self.currentToday isEqualToString:[NSString stringWithFormat:@"%ld-%ld-%ld",calendarModel.year,calendarModel.month,calendarModel.day]]) {
            calendarModel.isToDay = YES;
        }
        //判断选择的天 可能就是当天
        if ([self.selectedDay isEqualToString:[NSString stringWithFormat:@"%ld-%ld-%ld",calendarModel.year,calendarModel.month,calendarModel.day]]) {
            calendarModel.isSelected = YES;
        }
        [currentArray insertObject:calendarModel atIndex:index];
    }
    [currentArray sortUsingComparator:^NSComparisonResult(ScheduleCalendarModel *  _Nonnull obj1, ScheduleCalendarModel *  _Nonnull obj2) {
        return obj1.index > obj2.index;
    }];
}
#pragma mark - ScrollIndexPath
- (void)scrollIndexPath:(NSInteger)section shouldReloadData:(BOOL)reloadData animal:(BOOL)animal first:(BOOL)first
{
    if (reloadData) {
        [self.mainView reloadData];
    }
    if (first) {
        [self.mainView setContentOffset:CGPointMake(self.mainView.width * section, 0) animated:animal];
    } else {
        [self.mainView setContentOffset:CGPointMake(self.mainView.width*section, 0) animated:animal];
    }
}
#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.dataArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr[section].count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ScheduleCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    ScheduleCalendarModel *calendarModel = self.dataArr[indexPath.section][indexPath.row];
    cell.calendarModel = calendarModel;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ScheduleCalendarModel *calendarModel = self.dataArr[indexPath.section][indexPath.row];
    if (calendarModel.monthType == MonthTypeLast || calendarModel.monthType == MonthTypeNext) {
        return;
    }
    for (NSInteger index = 0; index < self.dataArr.count; index ++) {
        for (NSInteger flag = 0; flag < self.dataArr[index].count; flag ++) {
            ScheduleCalendarModel *itemCalendarModel = self.dataArr[index][flag];
            if (indexPath.section == index && indexPath.row == flag) {
                itemCalendarModel.isSelected = YES;
            } else {
                itemCalendarModel.isSelected = NO;
            }
        }
    }
    [collectionView reloadData];
    //回调年月日
    !self.BackDayTimeBlock ?: self.BackDayTimeBlock ([NSString stringWithFormat:@"%ld-%ld-%ld",calendarModel.year,calendarModel.month,calendarModel.day]);
    [self callBackCurrentDayData];
}
//手动滑动结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"滑动停止");
    [self loadDataScrollView:scrollView];
    [self createNetManager:NO];
}
- (void)loadDataScrollView:(UIScrollView *)scrollView
{
    if (scrollView != self.mainView) {
        return;
    }
    int index = scrollView.contentOffset.x / scrollView.frame.size.width;
    if (index < 0 || index > self.dataArr.count - 1) {
        return;
    }
    self.currentIndex = index;
    NSMutableArray *currentArray = self.dataArr[index];
    for (ScheduleCalendarModel *model in currentArray) {
        if (model.monthType != MonthTypeLast && model.monthType != MonthTypeNext) {
            self.currentYear = model.year;
            self.currentMonth = model.month;
            self.currentDay = model.day;
        }
    }
    if (self.currentIndex == 0 || self.currentIndex == self.dataArr.count - 1) {
        NSMutableArray *arr = [NSMutableArray array];
        if (self.currentIndex == 0) {
            //插入
            [self.dataArr insertObject:arr atIndex:0];
            [self updateDateYear:self.currentYear Month:self.currentMonth - 1 index:0];
            //不滑动
            [self scrollIndexPath:1 shouldReloadData:NO animal:NO first:NO];
        } else {
            //追加
            [self.dataArr addObject:arr];
            [self updateDateYear:self.currentYear Month:self.currentMonth + 1 index:self.dataArr.count - 1];
            //不滑动 刷新就行了
        }
        [self.mainView reloadData];
    }
    
    //回调月份
    !self.BackMonthBlock ?: self.BackMonthBlock ([NSString stringWithFormat:@"%ld年%ld月",self.currentYear,self.currentMonth]);
}
#pragma mark - 网络
- (void)createNetManager:(BOOL)active
{
    WK(weakSelf)
    NSLog(@"%ld,%ld %ld %ld",self.currentYear,self.currentMonth,self.currentIndex,self.dataArr.count);
    if (self.dataArr[self.currentIndex].count == 42) {
        if (self.dataArr[self.currentIndex][2].isLoadNetData) {
            NSLog(@"缓存了");
            //回调当天数据
            if (active) {
                [weakSelf callBackCurrentDayData];
            }
            return;
        }
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *year = [NSString stringWithFormat:@"%ld",self.currentYear];
    NSString *month = [NSString stringWithFormat:@"%ld",self.currentMonth];
    if (self.currentMonth < 10) {
        month = [NSString stringWithFormat:@"0%ld",self.currentMonth];
    }
    [parameters setValue:[NSString stringWithFormat:@"%@-%@",year,month] forKey:@"calendarTime"];
    [parameters setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    
    [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/sysOldCalendar/selectList"] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
        ScheduleCalendarServiceModel *responModel = [ScheduleCalendarServiceModel modelWithJSON:responseObject];
        if (responModel.success) {
            [weakSelf handleNetData:responModel];
            //回调当天数据
            if (active) {
                [weakSelf callBackCurrentDayData];
            }
        } else {
            [SVProgressHUD showWithStatus:responModel.message];
            [SVProgressHUD dismissWithDelay:1];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}
- (void)handleNetData:(ScheduleCalendarServiceModel *)serviceModel
{
    for (NSInteger index = 0; index < self.dataArr[self.currentIndex].count; index ++) {
        ScheduleCalendarModel *calendarModel = self.dataArr[self.currentIndex][index];
        for (NSInteger flag = 0; flag < serviceModel.data.count; flag ++) {
            ScheduleCalendarServiceDataModel *dataModel = serviceModel.data[flag];
            if ([calendarModel.dateStr isEqualToString:dataModel.jsonBody.yangli]) {
                calendarModel.isLoadNetData = YES;
                calendarModel.isChoice = dataModel.isChoice;
                calendarModel.isLuck = dataModel.isLuck;
                calendarModel.ji = dataModel.jsonBody.ji;
                calendarModel.yi = dataModel.jsonBody.yi;
                calendarModel.wanli = dataModel.detail;
                calendarModel.yinli = dataModel.jsonBody.yinli;
            }
        }
    }
    [self.mainView reloadData];
}
#pragma mark - 回调当天数据
- (void)callBackCurrentDayData
{
    NSLog(@"回调当天数据");
    for (NSInteger index = 0; index < self.dataArr[self.currentIndex].count; index ++) {
        ScheduleCalendarModel *itemModel = self.dataArr[self.currentIndex][index];
        if (itemModel.isSelected) {
            !self.BackDayDataModelBlock ?: self.BackDayDataModelBlock(itemModel);
        }
    }
}
#pragma mark - lazy懒加载
- (UIView *)headView
{
    if (!_headView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.width, 50*ADAPTER_WIDTH)];
        [self addSubview:view];
        view.backgroundColor = WhiteColor;
        
        NSArray *dataSource = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
        CGFloat itemWidth = self.width / 7;
        for (NSInteger index = 0; index < dataSource.count; index ++) {
            UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(itemWidth * index, 0, 44*ADAPTER_WIDTH, 50*ADAPTER_WIDTH)];
            [self addSubview:lab];
            lab.textColor = rgba(102, 102, 102, 1);
            lab.font = kFontRegular(14*ADAPTER_WIDTH);
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = dataSource[index];
        }
        _headView = view;
    }
    return _headView;
}
- (UICollectionView *)mainView
{
    if (!_mainView) {
        CGFloat itemWidth = self.width / 7;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.width, 6 * flowLayout.itemSize.height) collectionViewLayout:flowLayout];
        [self addSubview:collectionView];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[ScheduleCalendarCell class] forCellWithReuseIdentifier:@"Cell"];
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.pagingEnabled = YES;
        if (@available(iOS 11.0, *))
        {
            collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        _mainView = collectionView;
    }
    return _mainView;
}
- (NSMutableArray<NSMutableArray<ScheduleCalendarModel *> *> *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
@end
